<?php
/**
 * 图形处理工具 - 压缩 + 加水印，不做裁剪,统一生产jpg格式
 */
declare(encoding='UTF-8');

class ImageTranslate {
	//左上角
	const WATERMASK_POSITION_TOP_LEFT = 0;
	//左下角
	const WATERMASK_POSITION_BOTTOM_LEFT = 1;
	//右上角
	const WATERMASK_POSITION_TOP_RIGHT = 2;
	//右下角
	const WATERMASK_POSITION_BOTTOM_RIGHT = 3;
	//中间
	const WATERMASK_POSITION_CENTER = 4;

	/**
	 * 压缩处理，可选加水印
	 * @param string $dst				- 目标图像
	 * @param string $src				- 源图像
	 * @param int $quality				- 压缩质量 0 - 100
	 * @param string $watermask	- 水印图像
	 * @param int $wmPos				- 水印位置
	 * @throws Exception -- 抛出异常信息
	 */
	public static function compress($dst, $src, $quality = 80,  $watermask = null, $wmPos = self::WATERMASK_POSITION_BOTTOM_RIGHT) {
		if (!file_exists($src)) {
			throw new Exception("image file not found. [{$src}]");
		}

		if ($watermask != null && !file_exists($watermask)) {
			throw new Exception("watermask image file not found. [{$watermask}]");
		}

		/*$fileInfo = explode('/', mime_content_type($src));
		$extName = $fileInfo[1];*/
        $extName = pathinfo($src,PATHINFO_EXTENSION);
		$srcImage = null;
		switch ($extName) {
		    case 'octet-stream':
			case 'jpeg':
			case 'jpg':
				$srcImage = imagecreatefromjpeg($src);
				break;
			case 'png':
				$srcImage = imagecreatefrompng($src);
				break;
			case 'gif':
				$srcImage = imagecreatefromgif($src);
				break;
			case 'bmp':
				$srcImage = imagecreatefromwbmp($src);
				break;
			default:
				throw new Exception("invalid image. [$src]");
		}
		imagesavealpha($srcImage, true);

		if ($watermask != null) {
			//水印处理
			$extName = pathinfo($watermask, PATHINFO_EXTENSION);
			if ($extName != 'png') {
				throw new Exception("invalid watermask image, only support png image.");
			}
			$wmImage = imagecreatefrompng($watermask);
			$wmWidth = imagesx($wmImage);
			$wmHeight = imagesy($wmImage);

			$srcWidth = imagesx($srcImage);
			$srcHeight = imagesy($srcImage);

			//计算水印位置
			$px = 0;
			$py = 0;
			switch ($wmPos) {
				case self::WATERMASK_POSITION_BOTTOM_LEFT:
					$px = 0;
					$py = $srcHeight - $wmHeight;
					break;
				case self::WATERMASK_POSITION_TOP_RIGHT:
					$px = $srcWidth - $wmWidth;
					$py = 0;
					break;
				case self::WATERMASK_POSITION_BOTTOM_RIGHT:
					$px = $srcWidth - $wmWidth;
					$py = $srcHeight - $wmHeight;
					break;
				case self::WATERMASK_POSITION_CENTER:
					$px = $srcWidth/2 - $wmWidth/2;
					$py = $srcHeight/2 - $wmHeight/2;
					break;
			}

			imagesavealpha($wmImage, true);

			imagealphablending($srcImage, true);
			imagecopy($srcImage, $wmImage, $px, $py, 0, 0, $wmWidth, $wmHeight);
		}

		imagejpeg($srcImage, $dst, $quality);
	}
}